<template>
  <el-row :gutter="20" v-loading="loading">
    <el-col :xs="24" :sm="8">
      <!-- 智能客服输入 -->
      <el-card v-if="isShowModel" tabindex="-1" class="box-card">
        <component :is="getInterComponent(interData?.category)" :interData="interData" :category="interData.category" />
      </el-card>
    </el-col>
    <el-col :xs="24" :sm="8">
      <!-- 训练数据 -->
      <el-card v-if="isShowModel" class="box-card">
        <component :is="getInterComponent('TrainingData')" :interData="interData" />
      </el-card>
    </el-col>
    <el-col :xs="24" :sm="8">
      <el-card v-if="isShowModel" class="box-card">
        <component :is="getInterComponent('Dialogue')" :interData="interData" />
      </el-card>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { getSingleRobotInfo } from "@/api/cloud"
import { RobotListProps } from "@/api/cloud/types/cloud"
import { ElMessage } from "element-plus"
import Pubsub from "pubsub-js"
import { onBeforeUnmount, onMounted, onUpdated, ref } from "vue"
import Dialogue from "./components/dialogue.vue"
import IntelligentInput from "./components/intelligentInput.vue"
import InterForm from "./components/interForm.vue"
import TrainingData from "./components/trainingData.vue"

export interface IntelligentDataProps extends RobotListProps {}

const interData = ref<IntelligentDataProps>({} as IntelligentDataProps)
const loading = ref<boolean>(false)
const isShowModel = ref<boolean>(false)
const URL = new URLSearchParams(window.location.search)
const robotId = URL.get("id")

const CONFORM_LOADING = () => {
  Pubsub.subscribe("CONFORM_LOADING", () => {
    loading.value = true

    setTimeout(() => {
      loading.value = false
    }, 1000)
  })
}

const initRobotInfo = async (id: number) => {
  try {
    const { data, code } = await getSingleRobotInfo({ id })
    isShowModel.value = true
    if (code === 200) {
      interData.value = data
    } else {
      ElMessage({
        type: "error",
        message: "接口异常，用户信息读取失败"
      })
    }
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  CONFORM_LOADING()
  initRobotInfo(robotId)

  Pubsub.subscribe("UPDATE_SINGLE_ROBOT", async () => {
    await initRobotInfo(robotId)
  })
})

onUpdated(CONFORM_LOADING)

onBeforeUnmount(() => {
  Pubsub.unsubscribe("CONFORM_LOADING")
  Pubsub.unsubscribe("UPDATE_SINGLE_ROBOT")
})

const getInterComponent = (type: string) => {
  switch (type) {
    case "BASE":
      return IntelligentInput
    case "TrainingData":
      return TrainingData
    case "Dialogue":
      return Dialogue
    case "NPC":
    case "LAW":
    case "JSON":
    case "CPN":
    case "SHG":
    case "STAFF":
      return InterForm
    default:
      return null
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  height: calc(100vh - 120px);
  position: relative;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    width: 0;
  }
}

::v-deep .el-card__body {
  width: 100%;
  height: 100%;
}
</style>
